//
//  RequestExt.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/15.
//

import Foundation
import LeanCloud



func withTimeout<R>(timeout: TimeInterval, task: @escaping () async throws -> R) async throws -> R {
    
    let task = Task {
        try await task()
    }
    
    Task {
        try? await Task.sleep(until: .now + .seconds(timeout), clock: .continuous)
        task.cancel()
    }
    
    do {
        return try await task.value
    }catch{
        // 如果任务被取消，则我们知道任务超时了
        if task.isCancelled {
            throw MyError.Timeout
        }
        throw error
    }
}


//报错检测
public func check(_ suc:Bool,_ text:String)  throws -> Void {
    if !suc {
        throw MyError.checkParameter("common", text)
    }
}

//报错检测
public func check(_ suc:Bool,_ text:String, pre: @escaping () -> Void)  throws -> Void {
    if !suc {
        pre()
        throw MyError.checkParameter("common", text)
    }
}

//报错检测
public func check(_ tag: String, _ suc:Bool,_ text:String)  throws -> Void {
    if !suc {
        throw MyError.checkParameter(tag, text)
    }
}

//报错检测
public func check(_ tag: String, _ suc:Bool,_ text:String, pre: @escaping () -> Void)  throws -> Void {
    if !suc {
        pre()
        throw MyError.checkParameter(tag, text)
    }
}

//报错检测
public func check(_ suc:Bool, _ text: @escaping () -> String)  throws -> Void {
    if !suc {
        throw MyError.checkParameter("common", text())
    }
}

//报错检测
public func check(_ tag: String, _ suc:Bool, _ text: @escaping () -> String)  throws -> Void {
    if !suc {
        throw MyError.checkParameter(tag, text())
    }
}

//报错检测
public func check(_ suc: Bool,_ dict: @escaping () -> ServerException)  throws -> Void {
    if !suc {
        throw MyError.customize(dict().code, dict().message)
    }
}

// 重试函数, 将block的返回值，返回到 retry的值
public func retry<T>(maxRetries: Int, retryDelayMillis: TimeInterval, block: @escaping () async throws -> T) async throws -> T {
    do {
        return try await block()
    } catch {
        if maxRetries > 0 {
            try await Task.delay(retryDelayMillis / 1000.0) // 将毫秒转换为秒
            return try await retry(maxRetries: maxRetries - 1, retryDelayMillis: retryDelayMillis, block: block)
        } else {
            throw error // 重新抛出捕获的错误
        }
    }
}


extension Task where Success == Never, Failure == Never {
    // 使用毫秒作为参数
    static func delay(_ milliseconds: TimeInterval) async throws {
        // 1 毫秒 = 1_000_000 纳秒
        let nanoseconds = UInt64(milliseconds * 1_000_000)
        try await Task.sleep(nanoseconds: nanoseconds)
    }
}
